package com.wantup.demo01;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.util.concurrent.*;

/**
 * @ClassName TestThreadPool
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/6/27  0:13
 * @Version 1.0
 * 多线程的 还是要考虑 变量定义得位置。
 * 共享变量。
 *  线程池：底层维护了一个线程队列，队列中保存着所有等待状态的线程。
 *  避免了创建与销毁线程额外的开销。
 */

public class TestThreadPool {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        ThreadPoolDemo poolDemo = new ThreadPoolDemo();
//        new Thread(poolDemo,"1").start();
//        new Thread(poolDemo,"2").start();

        //1.创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
//        ThreadPoolDemo poolDemo2 = new ThreadPoolDemo();
//
//        //2.为线程池中的线程分配任务
//        for (int i = 0; i < 10; i++) {
//
//        executorService.submit(poolDemo2);
//        //executorService.submit(poolDemo2);
//        }
//
//        //3. 关闭线程池
//        executorService.shutdown();


        ///CallAble
        Future<Integer> future = executorService.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <=100; i++) {
                    sum += i;
                }

                return sum;
            }
        });


        System.out.println(future.get());
        executorService.shutdown();

    }

}

class ThreadPoolDemo implements Runnable {
    //共享变量
    private int i = 0;

    @Override
    public void run() {
        //int i = 0;//非共享变量
        while (i<=1000){
            System.out.println(Thread.currentThread().getName()+" : "+i++);
        }
    }
}





